#include "mergeSort.h"
#include "../stream/inputbufferstream.h"
#include "../stream/outputbufferstream.h"
#include <sstream>
#include<cstring>
#include <iostream>
#include<climits>
using namespace std;


void mergeSort(int num[], int temp[], int size)
{
	  split(num, temp, 0, size - 1);
}
 
void split(int num[], int temp[], int left, int right)
{
	int mid = (right+left)/2;
	 
	if (right > left)
	{
		split(num, temp, left, mid);
		split(num, temp, (mid+1), right);
		merge(num, temp, left, (mid+1), right);
	}
}

void merge(int num[],int temp[], int left, int mid, int right)
{
	int lend = mid -1,i = left, total = (right - left) + 1;

	while(left<=lend && mid<=right)
	{
		if(num[left] <= num[mid])
			temp[i++] = num[left++];
		else
			temp[i++] = num[mid++]; 
			
	}

	while(left<=lend)
		temp[i++] = num[left++];
	while(mid<=right)
		temp[i++] = num[mid++];

	for(int j=0;j<total;j++)
		num[right] = temp[right--];
}

int mergesortfile(char * fileName , int size)
{
	int *data = new int[size];
	int *temp = new int[size];
	inputbufferstream is;
	outputbufferstream os;
	is.open_s(fileName);
	int index = 0;
        while(!is.end_of_stream())
        {
        data[index++] = is.read_next();
        }
        is.close_i();
	mergeSort(data,temp,size);
        os.create("out");
        for (int i =0;i<size; i++)
        {
                os.write_s(data[i]);
        } 
        os.close_s();
        return 0;

}

int main(int argc , char * argv[])
{
if(argc!=4)
{
cout << " [exe] [filename] [size] [0] ";
return 0 ;
}
int size = atoi(argv[2]);
if(atoi(argv[3])==0)
{
mergesortfile(argv[1], size);
return 0;
}
}
